/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* findMiddle(ListNode* head)
    {
        ListNode* slow=head,*fast=head->next;
        // ListNode* pre=head;
        while(fast && fast->next)
        {
            // pre=slow;
            slow=slow->next;
            fast=fast->next->next;
        }
        // pre->next=nullptr;
        return slow;
    }
    ListNode* mergeList(ListNode* left,ListNode* right)
    {
        ListNode* hair=new ListNode();
        ListNode* cur=hair;
        while(left && right)
        {
            if(left->val<right->val)
            {
                cur->next=left;
                left=left->next;
                cur=cur->next;               
            }
            else{
                cur->next=right;
                right=right->next;
                cur=cur->next;
            } 
        }
        cur->next=left==nullptr?right:left;
        return hair->next;
    }
    ListNode* sortList(ListNode* head) {
        if(head==nullptr || head->next==nullptr)
            return head;
        
        ListNode* mid=findMiddle(head);
        ListNode* rightHead=mid->next;
        mid->next=nullptr;

        ListNode* left=sortList(head);
        ListNode* right=sortList(rightHead);
        return mergeList(left,right);

    }
};
